const dataType = data => {
    return Object.prototype.toString.call(data).slice(8, -1);
};

// 封装我的localStorge
const Storage = {
    /**
     * @desc 设置缓存 + 过期时间
     * @param {String} item
     * @param {any} value
     * @param {Number} expire
     */
    set(item, value, expire) {
        value = dataType(value) === 'Object' ? JSON.stringify(value) : value;
        if (expire) {
            value += '?expire=' + (this.getTime() + expire);
        }
        window.localStorage.setItem(item, value);
    },
    // 获取值
    get(item) {
        let data = window.localStorage.getItem(item) || '';
        let expireIndex = data.indexOf('?expire=');
        let expireTime = data.substring(expireIndex);
        let value = data.substring(0, expireIndex > 0 ? expireIndex : data.length);

        if (expireTime) {
            expireTime = expireTime.substring(8);
            if (expireTime < this.getTime()) {
                // 过期...
                this.clear(item);
                return '';
            } else {
                // 未过期...
                return this.getValue(value);
            }
        }
    },
    // 清除
    clear(item) {
        window.localStorage.removeItem(item);
    },
    // 获取当前时间
    getTime() {
        return new Date().getTime();
    },
    // 获取数据
    getValue(value) {
        // 这里还不够严谨, 判断json为数组和对象
        if (value.includes('{') || value.includes('[')) {
            return JSON.parse(value);
        } else {
            return value;
        }
    },
};

export {
    Storage
}